package com.linkage.seapeak.activity.project;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.FullyGridLayoutManager;
import com.linkage.jz.bankruptcy.base.BaseCreateActivity;
import com.linkage.jz.bankruptcy.bean.SearchDeclarationBean;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.FileUtil;
import com.linkage.jz.bankruptcy.widget.CommonPromptDialog;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.seapeak.base.BaseWhiteCreateActivity;
import com.linkage.seapeak.pojo.UploadImage;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class DissentAddActivity extends BaseWhiteCreateActivity {

    private EditText replyAdver;
    private TextView textSum;

    private RecyclerView recyclerAppendImgs;
    private List<UploadImage> imageListAppend = new ArrayList<>();
    private GridImagesAdapter imgAdapterAppend;

    private String creditorId;
    private String projectId;
    private String creditorRightReviewID;
    private int type;

    private PublicNoticeDialog noticeDialog;

//  type  0:管理人; 1:债权人
    public static void start(Context context, String creditorId, String projectId,
                             String creditorRightReviewID, int type) {
        Intent intent = new Intent(context, DissentAddActivity.class);
        intent.putExtra("creditorId", creditorId);
        intent.putExtra("projectId", projectId);
        intent.putExtra("creditorRightReviewID", creditorRightReviewID);
        intent.putExtra("type", type);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dissent_add, "异议");
        creditorId = getIntent().getStringExtra("creditorId");
        projectId = getIntent().getStringExtra("projectId");
        creditorRightReviewID = getIntent().getStringExtra("creditorRightReviewID");
        type = getIntent().getIntExtra("type", 0);

        addMenu(new MenuAction(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(replyAdver.getText().toString())) {
                    showToast("意见不可为空");
                    return;
                }

                if (type == 1) {
                    noticeDialog = new PublicNoticeDialog(DissentAddActivity.this, new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (v.getId() == R.id.btn_save_notice) {
                                sendDissent();
                            } else {
                                noticeDialog.dismiss();
                            }
                        }
                    }, 1, "提示", "确认录入异议信息？",
                            "取消", "确认");
                    noticeDialog.show();
                } else
                    sendDissent();
            }
        }, "提交", 0));
        initView();
    }

    @Override
    public void onBackPressed() {
        if (replyAdver.getText().toString().length() == 0) {
            super.onBackPressed();
        }

        noticeDialog = new PublicNoticeDialog(DissentAddActivity.this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.btn_save_notice) {
                    DissentAddActivity.super.onBackPressed();
                } else {
                    noticeDialog.dismiss();
                }
            }
        }, 1, "提示", "放弃编辑？",
                "否", "是");
        noticeDialog.show();
    }

    private void initView() {
        replyAdver = (EditText) findViewById(R.id.reply_adver);
        textSum = (TextView) findViewById(R.id.text_sum);
        recyclerAppendImgs = (RecyclerView) findViewById(R.id.recycler_append_imgs);

        recyclerAppendImgs.setLayoutManager(new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL,
                false));
        imgAdapterAppend = new GridImagesAdapter(this, TYPE_EDIT);

        imgAdapterAppend.setList(imageListAppend);
        recyclerAppendImgs.setAdapter(imgAdapterAppend);



        replyAdver.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String tempStr = replyAdver.getText().toString();
                if (tempStr.length() < 300) {
                    textSum.setText(tempStr.length() + "/300");
                } else {
                    replyAdver.setText(tempStr.substring(0, 300));
                    textSum.setText("300/300");
                }
            }
        });
    }

    private void sendDissent() {

        JSONArray fileArr = new JSONArray();
//        for (int i = 1; i < mImgList.size(); i++) {
//            fileArr.put(mImgList.get(i).parse2JSON());
//        }


        for (int i = 0; i < imageListAppend.size(); i++) {
            if (TextUtils.equals(imageListAppend.get(i).getFilename(), NAME_ADD)) {
                continue;
            }
            JSONObject obj = new JSONObject();
            try {
                if (FileUtil.isImage(imageListAppend.get(i).getFilename())) {
                    obj.putOpt("attachmentName", "相关附件" + (i + 1) + ".jpg");
                } else {
                    obj.putOpt("attachmentName", imageListAppend.get(i).getFilename());
                }
                obj.putOpt("attachmentDownloadAddress", imageListAppend.get(i).getFilepath());
                obj.putOpt("attachmentSize", imageListAppend.get(i).getFilesize());
                obj.putOpt("loadUrl", imageListAppend.get(i).getLoadUrl());
                fileArr.put(obj);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        Network.getAPIService()
                .addCrDecRevObj(getUserToken(), creditorId, projectId, creditorRightReviewID, replyAdver.getText().toString(),fileArr.toString(), type)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(new Throwable(json.get("msg").getAsString()));
                            return;
                        } else {
                            showToast("已提交！");
                            finish();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError( Throwable e ) {
                        super.onError(e);
                    }
                });
    }
}
